package com.sky.trade.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.api.client.UserFeignClient;
import com.sky.api.domain.dto.GoodsSalesDTO;
import com.sky.api.domain.entity.AddressBook;
import com.sky.api.domain.entity.Orders;
import com.sky.common.constant.MessageConstant;
import com.sky.common.context.BaseContext;
import com.sky.common.exception.AddressBookBusinessException;
import com.sky.common.exception.OrderBusinessException;
import com.sky.common.exception.ShoppingCartBusinessException;
import com.sky.common.result.PageResult;
import com.sky.common.utils.HttpClientUtil;
import com.sky.trade.domain.dto.*;
import com.sky.trade.domain.entity.OrderDetail;
import com.sky.trade.domain.entity.ShoppingCart;
import com.sky.trade.domain.vo.OrderPaymentVO;
import com.sky.trade.domain.vo.OrderStatisticsVO;
import com.sky.trade.domain.vo.OrderSubmitVO;
import com.sky.trade.domain.vo.OrderVO;
import com.sky.trade.mapper.OrderDetailMapper;
import com.sky.trade.mapper.OrderMapper;
import com.sky.trade.mapper.ShoppingCartMapper;
import com.sky.trade.service.OrderService;
import com.sky.trade.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author toki
 */
@Service
@Slf4j
@RequiredArgsConstructor
//@EnableFeignClients(clients = {UserFeignClient.class})
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final UserFeignClient userFeignClient;
    private final ShoppingCartMapper shoppingCartMapper;

    // 百度地图API
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.shop.baidu.ak}")
    private String ak;

    // 没有商户，不用这个
//    private final UserMapper userMapper;
//    private final WeChatPayUtil weChatPayUtil;
    private final WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO 订单信息
     * @return 订单提交结果
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 先处理各种业务异常（收货地址为空、超出配送范围、购物车为空）
        // 地址簿为空?
        AddressBook addressBook = userFeignClient.getById(ordersSubmitDTO.getAddressBookId()).getData();
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 检查当前用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        // 购物车为空?
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        final List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);

        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        // 订单号,设为当前系统时间戳
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        // 向订单表中插入订单1条信息
        orderMapper.insert(order);
        // 向订单详情表中插入订单详情多条信息
        // 遍历购物车，插入订单详情表
        // 这里可以用批量插入，提高效率
        final ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            // 订单详情
            final OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            // 设置订单ID
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetailList);
        // 下单成功则清空当前用户的购物车
        shoppingCartMapper.deleteByUserId(userId);
        // 封装VO返回结果
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderTime(order.getOrderTime())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO 订单支付信息
     * @return 订单支付结果
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;

        // 没有商户,跳过微信支付(前端直接重定向至支付成功页面)
        // 直接更新支付状态为已支付
        paySuccess(ordersPaymentDTO.getOrderNumber());
        // 直接返回空对象
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 订单号
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号和用户ID查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 通过WebSocket,向客户端浏览器发送消息
        Map<String, Object> map = new HashMap<>();
        //消息类型，1表示来单提醒
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息,格式为json字符串
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum  分页数
     * @param pageSize 每页条数
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return 历史订单分页信息
     */
    @Override
    public PageResult pageQueryUser(int pageNum, int pageSize, Integer status) {
        // 设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        final OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        final ArrayList<OrderVO> list = new ArrayList<>();

        if (page != null && page.getTotal() > 0) {
            // 查询出订单明细，并封装入OrderVO进行响应
            for (Orders orders : page) {
                // 订单id
                final Long orderId = orders.getId();
                // 根据ID查询订单详情
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                // 封装为OrderVO
                final OrderVO orderVO = new OrderVO();
                orderVO.setOrderDetailList(orderDetails);
                BeanUtils.copyProperties(orders, orderVO);

                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询订单详情
     *
     * @param id 订单id
     * @return 订单详情
     */
    @Override
    public OrderVO details(Long id) {
        // 根据订单id查询订单数据
        Orders orders = orderMapper.getById(id);
        // 根据该订单id查询菜品/套餐明细数据
        final List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 封装为OrderVO返回
        final OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id 订单id
     */
    @Override
    public void userCancelById(Long id) throws Exception {
        // 根据订单id查询订单数据
        final Orders orders = orderMapper.getById(id);

        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 判断订单状态
        final Integer status = orders.getStatus();
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (status > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 订单状态为 1待付款\2待接单 时，可以取消订单
        // 2待接单状态下且支付状态为已支付时取消订单，需先退款
        if (status.equals(Orders.TO_BE_CONFIRMED) && orders.getPayStatus().equals(Orders.PAID)) {
            // 调用微信支付退款接口
//            weChatPayUtil.refund(orders.getNumber(), //商户订单号
//                    orders.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
            // 模拟退款成功 直接将支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
            log.info("订单{}退款成功", orders.getNumber());
        }

        // 设置更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        // 更新订单
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id 订单id
     */
    @Override
    public void repetition(Long id) {
        // 当前用户ID
        final Long userId = BaseContext.getCurrentId();
        // 根据订单id查询订单详情数据
        final List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 将订单详情对象转换为购物车对象
        final ArrayList<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            final ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 条件搜索订单
     *
     * @param ordersPageQueryDTO 订单查询条件
     * @return 历史订单分页信息
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        final Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 获取订单VO列表
     *
     * @param page 订单分页对象
     * @return 订单VO列表
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();
        final List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                final OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders 订单对象
     * @return 订单详情字符串
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        final List<OrderDetail> orderDishList = orderDetailMapper.getByOrderId(orders.getId());
        final ArrayList<String> list = new ArrayList<>();
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        for (OrderDetail orderDetail : orderDishList) {
            final String s = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            list.add(s);
        }
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", list);
    }

    /**
     * 订单统计
     *
     * @return OrderStatisticsVO 订单统计信息
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        // 将查询出的数据封装到orderStatisticsVO中响应
        final OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.countStatus(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /**
     * 接单,将订单的状态修改为“已接单”
     *
     * @param ordersConfirmDTO 确认订单信息
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        final Orders orders = Orders.builder().
                id(ordersConfirmDTO.getId()).
                status(Orders.CONFIRMED).
                build();
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        final Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单 不存在(可能过期) 或 不为待接单状态 则不能拒单
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 若订单的支付状态为已付款,则需先申请退款
        if (orders.getPayStatus().equals(Orders.PAID)) {
//            String refund = weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
            log.info("订单{}退款中 ", orders.getNumber());
        }

        // 根据订单id更新订单状态、拒单原因、取消时间
        orders.setStatus(OrderVO.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        final Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        // 若已支付,则需先退款
        if (orders.getPayStatus().equals(Orders.PAID)) {
            log.info("订单{}退款中", orders.getNumber());
        }

        // 根据订单id更新订单状态、取消原因、取消时间
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        final Orders orders = orderMapper.getById(id);
        // 若订单 不存在 或 状态不为已接单,则不能进行派送操作
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        final Orders orders = orderMapper.getById(id);
        // 订单不存在 或 状态不为4派送中,则不能进行完成操作
        if (orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为完成,送达时间设为当前
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address 用户收货地址
     */
    private void checkOutOfRange(String address) {
        final HashMap<String, String> map = new HashMap<>();
        map.put("output", "json");
        map.put("ak", ak);

        // 地理编码服务（又名Geocoder）是一类Web API接口服务。
        // 用户可通过该功能，将结构化地址（省/市/区/街道/门牌号）解析为对应的位置坐标。
        // 地址结构越完整，地址内容越准确，解析的坐标精度越高。
        //获取店铺的经纬度坐标,格式为JSON
        map.put("address", shopAddress);
        final String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        // 解析json获取坐标
        JSONObject jsonObject = JSONObject.parseObject(shopCoordinate);
        // 服务码为0表正常状态
        if (!"0".equals(jsonObject.getString("status"))) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    @Override
    public void reminder(Long id) {
        final Orders orders = orderMapper.getById(id);
        // 订单不存在抛异常
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 通过WebSocket,向客户端浏览器发送消息
        Map<String, Object> map = new HashMap<>();
        //消息类型，2表示催单提醒
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public List<GoodsSalesDTO> getSalesTop10(LocalDateTime begin, LocalDateTime end) {
        return orderMapper.getSalesTop10(begin, end);
    }

    @Override
    public Double sumByMap(Map<String, Object> map) {
        return orderMapper.sumByMap(map);
    }

    @Override
    public Integer countByMap(Map<String, Object> map) {
        return orderMapper.countByMap(map);
    }


}


















